<template>
	<view class="container">
		<view class="search">
			<!-- @change="change"	@search="change" -->
			<u-search
				searchIconSize="40"
				height="72"
				shape="square"
				:showAction="false"
				bgColor="#F4F6F9"
				placeholder="输入邮件号搜索"
				v-model="query.keyword"
				clearabled
			></u-search>
		</view>

		<!-- 历史搜索 -->
		<view class="history">
			<view class="history-hd">
				<view class="history-hd-title">历史搜索</view>
				<view v-if="historyLists.length" class="history-hd-icon" @tap="searchDel('all')"><image :src="resBaseUrl + '/clear-draw.png'" mode="aspectFit"></image></view>
			</view>
			<view v-if="historyLists.length" class="historys-wrapper" :style="{ maxHeight: showHisMore ? 'unset' : '68px' }">
				<view class="historys">
					<block v-for="(item, index) in historyLists" :key="index">
						<view class="history-item">
							<text class="u-line-1" @tap.stop="chooseRecord(item)">{{ item }}</text>
							<view class="history-item-close" @tap.stop="searchDel(item)"><u-icon name="close" color="#586474" size="28"></u-icon></view>
						</view>
					</block>
					<view v-if="historyMore" class="history-item history-item-more">
						<u-icon :name="showHisMore ? 'arrow-up' : 'arrow-down'" color="#586474" size="28" @click="switchSearch"></u-icon>
					</view>
				</view>
			</view>
			<view v-else class="historys-none">输入邮件号搜索</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'search',
	data() {
		return {
			type: '',
			query: {
				keyword: '',
				page: 1,
				size: 15
			},
			total: 0,
			list: [],
			hotList: [],
			hotLoading: true,
			recommendQuery: {
				pageNum: 1,
				pageSize: 10,
				userId: ''
			},

			recommendLists: [],
			recommendLoading: true,

			// historyHeight: 0,
			// 搜索记录属性
			searchRecords: [],
			lowerSearchRecords: [],
			historyLists: [],
			historyMore: false, // 是否需要加载更多
			showHisMore: false, // 是否已经加载更多的状态

			searchQuery: {
				searchType: 1,
				size: 10,
				userId: ''
			},

			searchIng: false
		};
	},
	onLoad() {},
	methods: {
		chooseRecord(e) {
			let value = {
				keyword: e,
				page: 1,
				size: 15,
				type: 3
			};
			uni.$u.route('/pages/company/index', {
				value: JSON.stringify(value)
			});
		},
		jump() {
			if (!this.query.keyword.trim()) {
				uni.$u.toast('输入不能为空~');
				return;
			}
			let value = {
				...this.query,
				type: 3
			};
			uni.$u.route('/pages/company/index', {
				value: JSON.stringify(value)
			});
		},
		searchRecord() {
			this.$api.searchRecord(this.searchQuery).then(res => {
				this.historyLists = res && res.length ? res : [];
				this.searchRecords = uni.$u.deepClone(this.historyLists);
				this.$nextTick(() => {
					this.historyMore = false;
					this.calcHisItem();
				});
			});
		},
		searchAdd() {
			this.$api
				.searchAdd({
					searchType: 1,
					searchWord: this.query.keyword,
					userId: this.userInfo.userId
				})
				.then(res => {
					// this.searchRecord();
					// uni.hideLoading()
					// this.hotList = res && res.length ? res : [];
				});
			// .catch(err => {
			// 	// uni.hideLoading()
			// });
		},
		searchDel(e) {
			let searchWord = e === 'all' ? null : e;
			// uni.showLoading({
			// 	title: '删除中...'
			// });
			this.$api
				.searchDel({
					searchType: 1,
					searchWord,
					userId: this.userInfo.userId
				})
				.then(res => {
					// uni.hideLoading();
					this.searchRecord();
				})
				.catch(err => {
					// uni.hideLoading();
				});
		},
		join(str, key) {
			var reg = new RegExp(`(${key})`, 'gm');
			var replace = '<span class="search-keyword">$1</span>';
			return str.replace(reg, replace);
		},
		focusState(arr) {
			return new Promise((resolve, reject) => {
				let list = uni.$u.deepClone(arr);
				if (list.length > 0) {
					if (this.userInfo && this.userInfo.userId) {
						let companyIds = list.map(e => e.csfId);
						this.$api
							.focusState({
								companyIds,
								userId: this.userInfo.userId
							})
							.then(res => {
								list.forEach(l => {
									l.isFocus = res.find(e => e == l.csfId) ? true : false;
								});
								resolve(list);
							})
							.catch(err => {
								reject(false);
							});
					} else {
						resolve(list);
					}
				} else {
					resolve(list);
				}
			});
		},
		retrieval(first) {
			var _this = this;
			if (!this.query.keyword.trim()) {
				uni.$u.toast('输入不能为空~');
				return;
			}
			this.searchAdd();
			// uni.showLoading({
			// 	title: '加载中...'
			// });
			let query = uni.$u.deepClone(this.query);
			if (first) {
				this.list = [];
				query.page = 1;
			} else {
				query.page += 1;
			}

			let apiKey = this.type == 'around' ? 'nearby' : 'retrieval';
			this.$api[apiKey](query)
				.then(async res => {
					if (res.list && res.list.length) {
						_this.query.page = query.page;
						let list = res.list;
						// let list = await _this.focusState(res.list);
						list.forEach(e => {
							e.stdName = this.join(e.stdName, this.query.keyword);
							e.stock = e.stock ? this.join(e.stock, this.query.keyword) : '';
						});
						_this.list = [..._this.list, ...list];
					}
					_this.total = res.total;
					// uni.hideLoading();
				})
				.catch(err => {
					// uni.hideLoading();
				});
		},
		async focusDone() {
			let list = await this.focusState(this.list);
			this.list = list;
		},
		recommendList(first) {
			this.recommendLoading = true;
			let query = uni.$u.deepClone(this.recommendQuery);
			if (first) {
				this.recommendLists = [];
				query.pageNum = 1;
			} else {
				query.pageNum += 1;
			}

			this.$api
				.recommend(query)
				.then(res => {
					if (res && res.length) {
						this.recommendQuery.pageNum = query.pageNum;
						this.recommendLists = res;
					}
					this.recommendLoading = false;
				})
				.catch(err => {
					this.recommendLoading = false;
				});
		},
		hotRecommend() {
			this.hotLoading = true;
			this.$api
				.hotRecommend()
				.then(res => {
					this.hotLoading = false;
					this.hotList = res && res.length ? res : [];
				})
				.catch(err => {
					this.hotLoading = false;
				});
		},
		onCompany(item) {
			// let pages = getCurrentPages();
			// let prePage = pages ? pages[pages.length - 2] : '';
			// if (this.type == 'around' && prePage && prePage.__page__.route.indexOf('around') != -1) {
			// 	if (!item.location || !item.location.lat) {
			// 		uni.$u.toast('该企业信息缺少经纬度!');
			// 		return;
			// 	}
			// 	prePage.afterSearchFun(item);
			// 	uni.navigateBack({
			// 		delta: 1
			// 	});
			// } else {
			uni.$u.route('/pages/enterprise/detail', {
				csfId: item.csfId
			});
			// }
		},
		// 搜索框改变时候
		change(e) {
			if (e.trim()) {
				if (!this.searchIng) {
					this.searchIng = true;
				}
				this.retrieval(true);
			} else {
				this.searchIng = false;
				this.searchRecord();
				// this.$nextTick(() => {
				// 	this.calcHisItem();
				// });
				// console.log(this.searchIng);
			}
		},
		// calcHisHeight() {
		// 	var that = this;
		// 	const query = uni.createSelectorQuery().in(this);
		// 	query
		// 		.select('.historys')
		// 		.boundingClientRect(data => {
		// 			console.log(data);
		// 			if (data) {
		// 				if (data.height > 60) {
		// 					that.historyMore = true;
		// 					that.historyHeight = data.height;
		// 				} else {
		// 					that.historyMore = false;
		// 				}
		// 			}
		// 		})
		// 		.exec();
		// },
		switchSearch() {
			if (this.showHisMore) {
				this.historyLists = this.lowerSearchRecords;
				this.showHisMore = false;
			} else {
				this.historyLists = this.searchRecords;
				this.showHisMore = true;
			}
		},
		calcHisItem() {
			var that = this;
			let windowWidth = uni.getSystemInfoSync().screenWidth;
			windowWidth = windowWidth - 32;
			let total = 0;
			let row = 0;
			// 计算子项
			const query1 = uni.createSelectorQuery().in(this);
			query1
				.selectAll('.history-item')
				.boundingClientRect(data => {
					if (data) {
						// console.log(data);
						if (data && data.length) {
							data.map((e, index) => {
								total += e.width + 8;
								if (total > windowWidth) {
									row += 1;
									total = e.width + 8;
									if (row == 2) {
										that.lowerSearchRecords = that.historyLists.slice(0, index - 1);
										if (that.showHisMore) {
											that.historyLists = that.searchRecords;
										} else {
											that.historyLists = that.lowerSearchRecords;
										}
									}
								}
							});
							if (row > 1) {
								that.historyMore = true;
							} else {
								that.historyMore = false;
							}
						} else {
							that.lowerSearchRecords = [];
							that.historyLists = [];
							that.historyMore = false;
						}
						// console.log('historyMore', that.historyMore);
						// console.log(that.historyLists, that.lowerSearchRecords);
					}
				})
				.exec();
		}
	}
};
</script>

<style lang="scss" scoped>
.container,
.list {
	background: #ffffff;
}
.history {
	padding: 0 32rpx;
	.historys-none {
		min-height: 34px;
		font-size: 22rpx;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		color: #86909c;
	}
	&-hd {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		&-title {
			font-size: 28rpx;
			font-weight: 500;
			color: #1b253a;
		}
		&-icon {
			width: 32rpx;
			height: 32rpx;
		}
	}
	.historys-wrapper {
		transition: all 0.3s;
		overflow: hidden;
	}
	.historys {
		display: flex;
		flex-wrap: wrap;
		.history-item {
			display: flex;
			align-items: center;
			height: 50rpx;
			border-radius: 12rpx;
			font-size: 24rpx;
			margin: 0 16rpx 16rpx 0;
			color: #586474;
			background-color: #f4f6f9;
			text {
				display: block;
				padding: 0 8rpx 0 16rpx;
				max-width: 110px;
			}
			.history-item-close {
				margin-top: 2px;
				padding: 0 16rpx 0 8rpx;
			}
		}
		.history-item-more {
			padding: 0 16rpx;
			// margin-right: 120rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
}
.header {
	z-index: 99;
	position: fixed;
	left: 0;
	width: 100%;
	background: #ffffff;
	right: 0;
	top: 0;
}
.search {
	height: 88rpx;
	background: #fff;
	padding: 0 28rpx;
	display: flex;
	align-items: center;
	.back {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 40rpx;
		margin-right: 16rpx;
	}
}
.tabs {
	display: flex;
	align-items: center;
	padding: 0 8rpx;
	height: 88rpx;
	.tab {
		padding: 20rpx 24rpx;
		font-family: PingFangSC-Medium, PingFang SC;
		font-weight: 400;
	}
	.tab-active {
		font-weight: bold;
	}
}

.list {
	margin-top: 8rpx;
	padding: 0 32rpx;
	.list-item {
		border-bottom: 2rpx solid #e6e7ed;
	}
	.search-item-top {
		justify-content: space-between;
		border-bottom: 1px solid #e6e7ed;
		.search-item-content {
			flex: 1;
		}
	}
	.search-item {
		min-height: 48px;
		display: flex;
		align-items: center;
		// justify-content: space-between;
		.search-item-content {
			// flex: 1;
			display: flex;
			flex-direction: column;
			padding-left: 16rpx;
			&-bd {
				margin-top: 8rpx;
				font-size: 24rpx;
				color: #586474;
			}
			.search-keyword {
				color: #ed7b2e;
			}
		}
	}
}

.swiper-wrapper {
	margin-top: 32rpx;
	white-space: nowrap;
	height: 880rpx;
	width: 100%;
	position: relative;
	// padding-right: 32rpx;
	.swiper-wrapper-item {
		width: 520rpx;
		margin-left: 32rpx;
		height: 872rpx;
		display: inline-block;
		// height: 100%;
		padding: 24rpx 0;
		overflow: hidden;
		background: linear-gradient(180deg, rgba(248, 187, 33, 0.2) 0%, rgba(247, 187, 36, 0) 10%);
		box-shadow: 0px 4rpx 12rpx 0px rgba(20, 20, 21, 0.06);
		border-radius: 8rpx;
		&:last-child {
			margin-right: 32rpx;
		}
		.swiper-wrapper-item-title {
			display: flex;
			align-items: center;
			color: #b9540f;
			font-weight: bold;
			padding: 8rpx 24rpx 24rpx;
			.icon {
				width: 32rpx;
				height: 32rpx;
			}
			text {
				margin-left: 12rpx;
			}
		}
		.search-item {
			min-height: 76rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 24rpx;
			.search-item-index {
				font-size: 22rpx;
				color: #ffffff;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 32rpx;
				height: 32rpx;
				background: linear-gradient(180deg, #d1d7de 0%, #abb0ba 100%);
				border-radius: 4rpx;
			}
			.search-item-index-1 {
				background: linear-gradient(142deg, #ff7f49 0%, #ff3838 100%);
			}
			.search-item-index-2 {
				background: linear-gradient(142deg, #ffa749 0%, #ff7238 100%);
			}
			.search-item-index-3 {
				background: linear-gradient(142deg, #ffe18c 0%, #ff9b38 100%);
			}
			.search-item-heat {
				font-size: 22rpx;
				color: #86909c;
			}
			.search-item-content {
				flex: 1;
				font-size: 26rpx;
				color: #1b253a;
				padding-left: 16rpx;
				&-bd {
					margin-top: 8rpx;
					font-size: 24rpx;
					color: #586474;
				}
				.search-keyword {
					color: #ed7b2e;
				}
			}
		}
	}
}
</style>
